﻿using System;
using System.Collections;

namespace Jinndev {

    public class AsyncHandle : IEnumerator {

        public static AsyncHandle Empty => new AsyncHandle() { IsComplete = true };

        public static AsyncHandle Wrap(Action<Action> action) {
            var handle = new AsyncHandle();
            action(handle.Complete);
            return handle;
        }

        public object Current => null;
        public bool IsComplete { get; set; }

        private Action callback;

        public void Complete() {
            IsComplete = true;
            callback?.Invoke();
        }
        public bool MoveNext() {
            return !IsComplete;
        }

        public void Reset() {

        }

        public void OnComplete(Action callback) {
            this.callback = callback;
        }

    }

    public class AsyncHandle<T> : AsyncHandle {

        public new static AsyncHandle<T> Empty => new AsyncHandle<T>() { IsComplete = true };

        public static AsyncHandle<T> Wrap(Action<Action<T>> action) {
            var handle = new AsyncHandle<T>();
            action(handle.Complete);
            return handle;
        }

        public T Result { get; set; }

        private Action<T> callback;

        public void Complete(T result) {
            Result = result;
            Complete();
            callback?.Invoke(result);
        }

        public void OnComplete(Action<T> callback) {
            this.callback = callback;
        }

    }

}
